import { createSlice, Dispatch, PayloadAction } from '@reduxjs/toolkit'

import { postLoginUserLogin } from '@/services/user'
import { encode, getCookie, setCookie } from '@/utils/utils'
import { createAsyncAction } from './util'

interface UserState {
  token: string
}

const initialState: UserState = {
  token: getCookie('pcToken')
}

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUserItem(state, { payload }: PayloadAction<Partial<UserState>>) {
      return {
        ...state,
        ...payload
      }
    },
  },
})

export const { setUserItem } = userSlice.actions

export default userSlice.reducer

export const loginAsync = createAsyncAction<any, boolean>(payload => {
  return async (dispatch: Dispatch) => {
    const res: any = await postLoginUserLogin({
      loginNo: 17300000002,
      loginFrom: 1,
      osVersion: 'pc',
      password: encode(123456),
      clientType: 9,
      loginType: 1
    })

    if (res.messageCode === 1011) {
      console.log('res----------', res)
      setCookie('pcToken', res.token)

      dispatch(
        setUserItem({
          token: res.token,
        }),
      )

      return res.object
    }

    return false
  }
})

export const logoutAsync = () => {
  return async (dispatch: Dispatch) => {
    const keys = document.cookie.match(/[^ =;]+(?=\=)/g)
    if (keys) {
      for (let i = keys.length; i--;) {
        document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString()
      }
    }

    dispatch(
      setUserItem({
        token: '',
      }),
    )
  }
}
